import axios from 'axios';
import { observable, action } from 'mobx';
import { message } from 'antd';
import { compileStr, uncompileStr } from '../utils';

const st = window.sessionStorage.getItem('vf');

export default class Store {
	@observable history = null
	@observable userInfo = null;
	@observable userList = [];
	@observable token = st ? uncompileStr(st) : '';

	@action updateHistory = his => {
		this.history = his;
	}
	@action updateToken = str => {
		window.sessionStorage.setItem('vf', compileStr(str));
		this.token = str;
	}

	@action refeshUserInfo = async (token) => {
		console.log(token);
		const result = await axios.get('/api/tokentoinfo');
		if(result && result.success) {
			this.userInfo = result.data;
			return true;
		}
		return false;
	}

	@action login = async data => {
		const result = await axios.post('/api/login', data);
		if (result && result.success) {
			const { token, ...userInfo } = result.data;
			this.updateToken(token);
			this.userInfo = userInfo;
			return true;
		} else {
			message.error(result.msg);
			return false;
		}
	}

	@action githubLogin = async () => {
		let url = window.location.href;
		url = url.replace('#', '___');
		const result = await axios.get(`/api/login-github?origin=${url}`);
		if (result && result.success) {
			console.log(result.data);
			window.location.href = result.data.path;
		} else {
			message.error(result.msg);
			return false;
		}
	}

	@action getList = async () => {
		const result = await axios.get('/api/users');
		if(result && result.success) {
			this.userList = result.data;
			return true;
		}else {
			message.error(result.msg);
			return false;
		}
	}

}